package net.starwifi.duobao.utils;

import java.text.DateFormat;
import java.text.SimpleDateFormat;

/**
 * ID主键生成器(14位,支持0.1毫秒99个订单,支持10台服务器节点)
 * Created by ruo on 2015/3/2.
 */
public class IDGenerate {


    private static IDGenerate idGenerate=null;

    private static Integer randomValue=0;

    /** 当前服务器节点. */
    private int serverNode;

    /** 不允许实例化. */
    private IDGenerate(int serverNode){
        this.serverNode=serverNode;
    }


    /** 唯一实例 */
    public synchronized static IDGenerate getInstance(int serverNode){
        if(idGenerate==null){
            idGenerate=new IDGenerate(serverNode);
        }
        return idGenerate;
    }

    /**
     * ID生成.
     * */
    public synchronized Long getID(){
         DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
        // String s=format.format(System.currentTimeMillis())+""+serverNode+""+ getRandomStr();
        //String s=format.format(System.currentTimeMillis())+""+serverNode;
        String s=format.format(System.currentTimeMillis())+getRandomStr();
        return Long.parseLong(s);
    }

    /**
     * 生成夺宝ID.
     * */
    public synchronized Long getDBID(){
        DateFormat format = new SimpleDateFormat("yyMMddHHmmss");
        String s=format.format(System.currentTimeMillis());
        return Long.parseLong(s);
    }

    /**
     * ID生成.
     * */
    public synchronized Long getFQGID(){
        DateFormat format = new SimpleDateFormat("yyMMddHHmm");
        // String s=format.format(System.currentTimeMillis())+""+serverNode+""+ getRandomStr();
        //String s=format.format(System.currentTimeMillis())+""+serverNode;
        String s=format.format(System.currentTimeMillis())+getRandomStr();
        return Long.parseLong(s);
    }

    private  String getRandomStr(){
        randomValue=randomValue+1;
        if(randomValue>100){
            randomValue=0;
        }
        String result=randomValue.toString();
        int i=2-(randomValue+"").length();
        if(i>0){
            for(int j=0;j<i;j++){
                result="0"+result;
            }
        }
        return result;
    }

}
